package cn.znzz.cjm.service.impl;

import cn.hutool.http.HttpUtil;
import cn.znzz.cjm.domain.LoginUser;
import cn.znzz.cjm.domain.UserMeal;
import cn.znzz.cjm.dto.LoginDto;
import cn.znzz.cjm.mapper.LoginUserMapper;
import cn.znzz.cjm.mapper.UserMealMapper;
import cn.znzz.cjm.oauth.Oauth2ClientDetails;
import cn.znzz.cjm.oauth.OauthClientDetailsProperties;
import cn.znzz.cjm.service.ILoginUserService;
import cn.znzz.cjm.util.AjaxResult;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.netflix.discovery.converters.Auto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chenjiangmin
 * @since 2021-12-16
 */
@Service
public class LoginUserServiceImpl extends ServiceImpl<LoginUserMapper, LoginUser> implements ILoginUserService {

    @Autowired
    private LoginUserMapper loginUserMapper;

    @Autowired
    private UserMealMapper userMealMapper;
    @Override
    public AjaxResult tenantEntering(LoginUser loginUser) {
        //保存t_login_user
        loginUserMapper.insert(loginUser);
        //获取保存的loginuser的主键
        Long id = loginUser.getId();
        //保存套餐信息
        UserMeal userMeal = new UserMeal();
        userMeal.setMealId(loginUser.getMealid());
        userMeal.setLoginId(id);
        userMealMapper.insert(userMeal);
        //返回loginuser的主键
        return AjaxResult.me().setResultObj(id);
    }

    @Autowired
    private OauthClientDetailsProperties oauthClientDetailsProperties;

    @Override
    public AjaxResult login(LoginDto dto) {
        String url="http://localhost:1040/oauth/token?client_id=%s&client_secret=%s&grant_type=password&redirect_uri=http://www.baidu.com&username=%s&password=%s";
        String clientId;
        String clientSecret;
        /*if(dto.getType()==0){
            clientId="admin";
            clientSecret="1";
        }else{
            clientId="website";
            clientSecret="1";
        }*/
        Oauth2ClientDetails oauth2ClientDetails = oauthClientDetailsProperties.getOauth2ClientDetails(dto.getType());
        url=String.format(url, oauth2ClientDetails.getClientId(), oauth2ClientDetails.getSecret(), dto.getUsername(), dto.getPassword());
        String s = HttpUtil.get(url);
        Map<String ,Object> map = JSON.parseObject(s, Map.class);
        return AjaxResult.me().setResultObj(map);
    }
}
